package com.onsproject.nzbgetremote;

import java.util.HashMap;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class StatusFragment extends Fragment {

	private LoadInfoTask mTask;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return inflater.inflate(R.layout.status_fragment, container, false);
	}

	@Override
	public void onResume() {
		super.onResume();
		mHandler.sendEmptyMessage(1);
	}

	@Override
	public void onDestroy() {
		mHandler.removeMessages(0);
		mHandler.removeMessages(1);
		super.onDestroy();
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				mHandler.sendEmptyMessageDelayed(1, 1000);
			} else if (msg.what == 1) {
				if (mTask != null) {
					mTask.cancel(true);
					mTask = null;
				}
				mTask = new LoadInfoTask();
				mTask.execute("");
			}
		};
	};

	private class LoadInfoTask extends AsyncTask<String, String, Boolean> {

		private HashMap<String, String> mStatusMap;

		@SuppressWarnings("unchecked")
		@Override
		protected Boolean doInBackground(String... params) {
			Settings settings = Settings.getInstance(getActivity());
			mStatusMap = (HashMap<String, String>) settings.callMethod(getActivity(), "status");
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			Integer uptime = Integer.valueOf(String.valueOf(mStatusMap.get("UpTimeSec")));
			int hours = uptime / 3600;
			int minutes = (uptime % 3600) / 60;
			int seconds = uptime % 60;

			String timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);

			if (getActivity() != null) {
				((TextView) getActivity().findViewById(R.id.uptimeText)).setText(timeString);
				((TextView) getActivity().findViewById(R.id.downloadedText)).setText(String.valueOf(mStatusMap.get("DownloadedSizeMB")) + " MB");
				((TextView) getActivity().findViewById(R.id.remainingText)).setText(String.valueOf(mStatusMap.get("RemainingSizeMB")) + " MB");
				((TextView) getActivity().findViewById(R.id.pausedText)).setText(String.valueOf(mStatusMap.get("ServerPaused")));
				mHandler.sendEmptyMessage(0);
			}
		};
	};
}
